package org.spruice;

import org.spruice.proxy.BeanCallback;

import java.lang.reflect.Method;

/**
 * User: mrettig
 * Date: Aug 19, 2008
 * Time: 5:18:31 PM
 */
public class ContextLifecycle implements org.springframework.context.Lifecycle {

    private String startMethod;
    private boolean running;
    private String stopMethod;
    private Object target;

    public String getStopMethod() {
        return stopMethod;
    }

    public void setStopMethod(String stopMethod) {
        this.stopMethod = stopMethod;
    }

    public Object getTarget() {
        return target;
    }

    public void setTarget(Object target) {
        this.target = target;
    }

    public String getStartMethod() {
        return startMethod;
    }

    public void setStartMethod(String startMethod) {
        this.startMethod = startMethod;
    }

    public void start() {
        this.running = true;
        invoke(startMethod);
    }

    public void stop() {
        this.running = false;
        invoke(stopMethod);
    }

    private void invoke(String method) {
        if (method == null)
            return;
        try {
            Method m = this.target.getClass().getMethod(method);
            BeanCallback.invoke(target, m);
        } catch (NoSuchMethodException e) {
            throw new RuntimeException(method, e);
        }
    }

    public boolean isRunning() {
        return this.running;
    }
}
